package com.dlwx.firefighting.utils;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.ColorMatrix;
import android.graphics.ColorMatrixColorFilter;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.PixelFormat;
import android.graphics.PorterDuff.Mode;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.media.ExifInterface;
import android.net.Uri;
import android.view.View;

import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

/**
 * Image处理工具类
 * 
 * @author songdy
 * 
 */
public class BitmapImageUtil {

	/**
	 * 将Drawable 转化为Bitmap
	 * 
	 * @param drawable
	 * @return
	 */
	public static Bitmap drawableToBitmapPro(Drawable drawable) {
		BitmapDrawable bd = (BitmapDrawable) drawable;
		return bd.getBitmap();
	}

	/**
	 * 将Bitmap转化为Drawable
	 * 
	 * @param bitmap
	 * @return
	 */
	public static Drawable BitmapToDrawable(Bitmap bitmap) {
		BitmapDrawable bitmapDrawable = new BitmapDrawable(bitmap);
		// BitmapDrawable bitmapDrawable = (BitmapDrawable)bitmap;
		return (Drawable) bitmapDrawable;
	}

	/**
	 * 将View转化为Bitmap
	 * 
	 * @param view
	 * @return
	 */
	public static Bitmap getViewBitmap(View view) {

		view.clearFocus();
		view.setPressed(false);
		boolean willNotCache = view.willNotCacheDrawing();
		view.setWillNotCacheDrawing(false);
		// Reset the drawing cache background color to fully transparent
		// for the duration of this operation
		int color = view.getDrawingCacheBackgroundColor();
		view.setDrawingCacheBackgroundColor(0);
		if (color != 0) {
			view.destroyDrawingCache();
		}
		view.buildDrawingCache();
		Bitmap cacheBitmap = view.getDrawingCache();
		if (cacheBitmap == null) {
			// LogUtil.e("", "failed getViewBitmap(" + view + ")", new
			// RuntimeException());
			return null;
		}
		Bitmap bitmap = Bitmap.createBitmap(cacheBitmap);
		// Restore the view
		view.destroyDrawingCache();
		view.setWillNotCacheDrawing(willNotCache);
		view.setDrawingCacheBackgroundColor(color);

		return bitmap;
	}

	public static InputStream getRequest(String path) throws Exception {
		URL url = new URL(path);
		HttpURLConnection conn = (HttpURLConnection) url.openConnection();
		conn.setRequestMethod("GET");
		conn.setConnectTimeout(5000);
		if (conn.getResponseCode() == 200) {
			return conn.getInputStream();
		}
		return null;
	}

	public static byte[] readInputStream(InputStream inStream) throws Exception {
		ByteArrayOutputStream outSteam = new ByteArrayOutputStream();
		byte[] buffer = new byte[4096];
		int len = 0;
		while ((len = inStream.read(buffer)) != -1) {
			outSteam.write(buffer, 0, len);
		}
		outSteam.close();
		inStream.close();
		return outSteam.toByteArray();
	}

	public static Drawable loadImageFromUrl(String url) {
		URL m;
		InputStream i = null;
		try {
			m = new URL(url);
			i = (InputStream) m.getContent();
		} catch (MalformedURLException e1) {
			e1.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		Drawable d = Drawable.createFromStream(i, "src");
		return d;
	}

	public static Drawable getDrawableFromUrl(String url) throws Exception {
		return Drawable.createFromStream(getRequest(url), null);
	}

	public static Bitmap getBitmapFromUrl(String url) throws Exception {
		byte[] bytes = getBytesFromUrl(url);
		return byteToBitmap(bytes);
	}

	public static Bitmap getRoundBitmapFromUrl(String url, int pixels)
			throws Exception {
		byte[] bytes = getBytesFromUrl(url);
		Bitmap bitmap = byteToBitmap(bytes);
		return toRoundCorner(bitmap, pixels);
	}

	public static Drawable geRoundDrawableFromUrl(String url, int pixels)
			throws Exception {
		byte[] bytes = getBytesFromUrl(url);
		BitmapDrawable bitmapDrawable = (BitmapDrawable) byteToDrawable(bytes);
		return toRoundCorner(bitmapDrawable, pixels);
	}

	public static byte[] getBytesFromUrl(String url) throws Exception {
		return readInputStream(getRequest(url));
	}

	public static Bitmap byteToBitmap(byte[] byteArray) {
		if (byteArray.length != 0) {
			return BitmapFactory
					.decodeByteArray(byteArray, 0, byteArray.length);
		} else {
			return null;
		}
	}

	public static Drawable byteToDrawable(byte[] byteArray) {
		ByteArrayInputStream ins = new ByteArrayInputStream(byteArray);
		return Drawable.createFromStream(ins, null);
	}

	public static Bitmap drawableToBitmap(Drawable drawable) {

		Bitmap bitmap = Bitmap
				.createBitmap(
						drawable.getIntrinsicWidth(),
						drawable.getIntrinsicHeight(),
						drawable.getOpacity() != PixelFormat.OPAQUE ? Config.ARGB_8888
								: Config.RGB_565);
		Canvas canvas = new Canvas(bitmap);
		drawable.setBounds(0, 0, drawable.getIntrinsicWidth(),
				drawable.getIntrinsicHeight());
		drawable.draw(canvas);
		return bitmap;
	}

	/**
	 * 图片去色,返回灰度图片
	 * 
	 * @param bmpOriginal
	 *            传入的图片
	 * @return 去色后的图片
	 */
	public static Bitmap toGrayscale(Bitmap bmpOriginal) {
		int width, height;
		height = bmpOriginal.getHeight();
		width = bmpOriginal.getWidth();

		Bitmap bmpGrayscale = Bitmap.createBitmap(width, height,
				Config.RGB_565);
		Canvas c = new Canvas(bmpGrayscale);
		Paint paint = new Paint();
		ColorMatrix cm = new ColorMatrix();
		cm.setSaturation(0);
		ColorMatrixColorFilter f = new ColorMatrixColorFilter(cm);
		paint.setColorFilter(f);
		c.drawBitmap(bmpOriginal, 0, 0, paint);
		return bmpGrayscale;
	}

	/**
	 * 去色同时加圆角
	 * 
	 * @param bmpOriginal
	 *            原图
	 * @param pixels
	 *            圆角弧度
	 * @return 修改后的图片
	 */
	public static Bitmap toGrayscale(Bitmap bmpOriginal, int pixels) {
		return toRoundCorner(toGrayscale(bmpOriginal), pixels);
	}

	/**
	 * 把图片变成圆角
	 * 
	 * @param bitmap
	 *            需要修改的图片
	 * @param pixels
	 *            圆角的弧度
	 * @return 圆角图片
	 */
	public static Bitmap toRoundCorner(Bitmap bitmap, int pixels) {
		// 创建一个和原始图片一样大小位图
		Bitmap roundConcerImage = Bitmap.createBitmap(bitmap.getWidth(),
				bitmap.getHeight(), Config.ARGB_8888);
		// 创建带有位图roundConcerImage的画布
		Canvas canvas = new Canvas(roundConcerImage);

		// int color = 0xff424242;
		// 创建画笔
		Paint paint = new Paint();
		// 创建一个和原始图片一样大小的矩形
		Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());
		RectF rectF = new RectF(rect);
		float roundPx = pixels;
		// 去锯齿
		paint.setAntiAlias(true);
		// canvas.drawARGB(0, 0, 0, 0);
		// paint.setColor(color);
		// 画一个和原始图片一样大小的圆角矩形
		canvas.drawRoundRect(rectF, roundPx, roundPx, paint);
		// 设置相交模式
		paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
		// 把图片画到矩形去
		canvas.drawBitmap(bitmap, null, rect, paint);

		return roundConcerImage;
	}

	/**
	 * 使圆角功能支持BitampDrawable
	 * 
	 * @param bitmapDrawable
	 * @param pixels
	 * @return
	 */
	public static BitmapDrawable toRoundCorner(BitmapDrawable bitmapDrawable,
			int pixels) {
		Bitmap bitmap = bitmapDrawable.getBitmap();
		bitmapDrawable = new BitmapDrawable(toRoundCorner(bitmap, pixels));
		return bitmapDrawable;
	}

	/**
	 * 
	 * @param d
	 * @return
	 */
	public static byte[] drawable2Bytes(Drawable d) {
		Bitmap bitmap = ((BitmapDrawable) d).getBitmap();
		return Bitmap2Bytes(bitmap);
	}

	/**
	 * 将图片内容解析成字节数组
	 * @param inStream
	 * @return byte[]
	 * @throws Exception
	 */
	public static byte[] readStream(InputStream inStream) throws Exception {
		byte[] buffer = new byte[1024];
		int len = -1;
		ByteArrayOutputStream outStream = new ByteArrayOutputStream();
		while ((len = inStream.read(buffer)) != -1) {
			outStream.write(buffer, 0, len);
		}
		byte[] data = outStream.toByteArray();
		outStream.close();
		inStream.close();
		return data;

	}

	/**
	 *  将字节数组转换为ImageView可调用的Bitmap对象
	 * @param bytes
	 * @param opts
	 * @return Bitmap
	 */
	public static Bitmap getPicFromBytes(byte[] bytes,
			BitmapFactory.Options opts) {
		if (bytes != null)
			if (opts != null)
				return BitmapFactory.decodeByteArray(bytes, 0, bytes.length,
						opts);
			else
				return BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
		return null;
	}

	/**
	 *  图片缩放
	 * @param bitmap
	 *            对象
	 * @param w
	 *            要缩放的宽度
	 * @param h
	 *            要缩放的高度
	 * @return newBmp 新 Bitmap对象
	 */
	public static Bitmap zoomBitmap(Bitmap bitmap, int w, int h) {
		int width = bitmap.getWidth();
		int height = bitmap.getHeight();
		Matrix matrix = new Matrix();
		float scaleWidth = ((float) w / width);
		float scaleHeight = ((float) h / height);
		matrix.postScale(scaleWidth, scaleHeight);
		Bitmap newBmp = Bitmap.createBitmap(bitmap, 0, 0, width, height,
				matrix, true);
		return newBmp;
	}

	/**
	 * 把Bitmap转Byte
	 * 
	 * @Author HEH
	 * @EditTime 2010-07-19 上午11:45:56
	 */
	public static byte[] Bitmap2Bytes(Bitmap bm) {
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		// bm.compress(Bitmap.CompressFormat.PNG, 100, baos);
		bm.compress(Bitmap.CompressFormat.JPEG, 80, baos);
		return baos.toByteArray();
	}

	/**
	 * 把字节数组保存为一个文件
	 * 
	 * @Author HEH
	 * @EditTime 2010-07-19 上午11:45:56
	 */
	public static File getFileFromBytes(byte[] b, String outputFile) {
		BufferedOutputStream stream = null;
		File file = null;
		try {
			file = new File(outputFile);
			FileOutputStream fstream = new FileOutputStream(file);
			stream = new BufferedOutputStream(fstream);
			stream.write(b);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (stream != null) {
				try {
					stream.close();
				} catch (IOException e1) {
					e1.printStackTrace();
				}
			}
		}
		return file;
	}

	/**
	 * 按固定比例进行缩放
	 * 
	 * @return
	 */
	public static Bitmap zoomImageByFixedRatio(String filePath, int size) {
		
		BitmapFactory.Options options = new BitmapFactory.Options();
		options.inJustDecodeBounds = true;

		// 由于设置inJustDecodeBounds为true，因此执行下面代码后bitmap为空
		Bitmap mBitmap = BitmapFactory.decodeFile(filePath, options);

		// 计算缩放比例，由于是固定比例缩放，只用高或者宽其中一个数据进行计算即可
		int scale = (int) (options.outHeight / (float) size);

		// 因为结果为int型，如果相除后值为0.n，则最终结果将是0
		if (scale <= 0) {
			scale = 1;
		}

		// LogUtil.i(this, "Scale=" + scale);

		options.inSampleSize = scale;
		options.inJustDecodeBounds = false;

		// 重新读入图片，注意此时已经把options.inJustDecodeBounds设回false
		mBitmap = BitmapFactory.decodeFile(filePath, options);

		return mBitmap;
	}
	
	/**
	 * 将图片旋转
	 * @param b
	 * @param degrees
	 * @return
	 */
	public static Bitmap rotate(Bitmap b, int degrees) {

		if (degrees != 0 && b != null) {
			int w = b.getWidth();  
			int h = b.getHeight();
			Matrix m = new Matrix();
			m.postRotate(degrees);  
//			m.setRotate(degrees, (float) b.getHeight() / 2,
//					(float) b.getWidth() / 2);
			try {
				Bitmap b2 = Bitmap.createBitmap(b, 0, 0, w,
						h, m, true);
				if (b != b2) {
					b.recycle();
					b = b2;
				}
			} catch (OutOfMemoryError ex) {
				return b;
				// Android123建议大家如何出现了内存不足异常，最好return 原始的bitmap对象。.
			} catch (Exception e) {
				return b;
			}
		}

		return b;

	}
	
	public static Bitmap decodeUriAsBitmap(Uri uri,Context content) {
		Bitmap bitmap = null;
		try {
			bitmap = BitmapFactory.decodeStream(content.getContentResolver()
					.openInputStream(uri));
		} catch (Exception e) {
			return bitmap;
		}
		return bitmap;
	}

	/**
	 * 按长宽各自比例进行缩放
	 * 
	 * @return
	 */
	public static Bitmap zoomImageByEachRatio(String filePath, int sWidth,
			int sHeight) {
	
		BitmapFactory.Options options = new BitmapFactory.Options();

		options.inJustDecodeBounds = false;

		Bitmap	mBitmap = BitmapFactory.decodeFile(filePath, options);

		int bmpWidth = mBitmap.getWidth();

		int bmpHeight = mBitmap.getHeight();

		// 缩放图片的尺寸

		float scaleWidth = (float) sWidth / bmpWidth; // 按固定大小缩放 sWidth 写多大就多大

		float scaleHeight = (float) sHeight / bmpHeight; //

		Matrix matrix = new Matrix();

		matrix.postScale(scaleWidth, scaleHeight);// 产生缩放后的Bitmap对象

		Bitmap resizeBitmap = Bitmap.createBitmap(mBitmap, 0, 0, bmpWidth,
				bmpHeight, matrix, false);

		mBitmap.recycle();

		return resizeBitmap;
	}

	/**
	 * 图片解析
	 *
	 * @param path
	 * @param targetWidth
	 * @param targetHeight
	 * @return
	 */
	public static Bitmap decodeScaleImage(String path, int targetWidth, int targetHeight) {
		BitmapFactory.Options bitmapOptions = getBitmapOptions(path);
		bitmapOptions.inSampleSize = calculateInSampleSize(bitmapOptions, targetWidth, targetHeight);
		bitmapOptions.inJustDecodeBounds = false;
		Bitmap noRotatingBitmap = BitmapFactory.decodeFile(path, bitmapOptions);
		int degree = readPictureDegree(path);

		Bitmap rotatingBitmap;
		if (noRotatingBitmap != null && degree != 0) {
			rotatingBitmap = rotatingImageView(degree, noRotatingBitmap);
			noRotatingBitmap.recycle();
			return rotatingBitmap;
		} else {
			return noRotatingBitmap;
		}
	}

	/**
	 * 获取BitmapFactory.Options
	 *
	 * @param pathName
	 * @return
	 */
	public static BitmapFactory.Options getBitmapOptions(String pathName) {
		BitmapFactory.Options opts = new BitmapFactory.Options();
		opts.inJustDecodeBounds = true;
		BitmapFactory.decodeFile(pathName, opts);
		return opts;
	}

	/**
	 * 计算样本大小
	 *
	 * @param options
	 * @param targetWidth
	 * @param targetHeight
	 * @return
	 */
	public static int calculateInSampleSize(BitmapFactory.Options options, int targetWidth, int targetHeight) {
		int height = options.outHeight;
		int width = options.outWidth;
		int scale = 1;
		if (height > targetHeight || width > targetWidth) {
			int heightScale = Math.round((float) height / (float) targetHeight);
			int widthScale = Math.round((float) width / (float) targetWidth);
			scale = heightScale > widthScale ? heightScale : widthScale;
		}
		return scale;
	}

	/**
	 * 获取图片角度
	 *
	 * @param filename
	 * @return
	 */
	public static int readPictureDegree(String filename) {
		short degree = 0;
		try {
			ExifInterface exifInterface = new ExifInterface(filename);
			int anInt = exifInterface.getAttributeInt(ExifInterface.TAG_ORIENTATION, 1);
			switch (anInt) {
				case ExifInterface.ORIENTATION_ROTATE_180:
					degree = 180;
				case ExifInterface.ORIENTATION_FLIP_VERTICAL:
				case ExifInterface.ORIENTATION_TRANSPOSE:
				case ExifInterface.ORIENTATION_TRANSVERSE:
				default:
					break;
				case ExifInterface.ORIENTATION_ROTATE_90:
					degree = 90;
					break;
				case ExifInterface.ORIENTATION_ROTATE_270:
					degree = 270;
			}
		} catch (IOException e) {
			e.printStackTrace();
		}

		return degree;
	}

	/**
	 * 旋转ImageView
	 *
	 * @param degree
	 * @param source
	 * @return
	 */
	public static Bitmap rotatingImageView(int degree, Bitmap source) {
		Matrix matrix = new Matrix();
		matrix.postRotate((float) degree);
		return Bitmap.createBitmap(source, 0, 0, source.getWidth(), source.getHeight(), matrix, true);
	}




}